<template>
  <div id="client">
    <el-card>
      <el-breadcrumb separator="/" separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>沟通管理</el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>
    <div>
      <div style="display: flex; justify-content: left">
        <!-- 左侧用户列表 -->
        <div class="left">
          <div
            class="lists"
            v-for="user in filteredUserList"
            :key="user.userId"
            @click="selectUser(user)"
            :style="{
              cursor: 'pointer',
              background:
                selectedUser && selectedUser.userId === user.userId
                  ? '#0c459a4f'
                  : '',
            }"
          >
          <img
                  style="width: 3rem; height: 3rem"
                  src="@/assets/xiang.png"
                  alt=""
                />
            <!-- 气泡 -->
            <div v-if="user.hasNewMessage" class="bubble"></div>
            <section style="width: 100%; margin-left: 6px; height: 3rem">
              <div style="height: 50%; font-size: 1.3rem;color: #ffffff;">
                {{ user.username }}
              </div>
              <div  style="height: 50%; color: #f2ebebcf;">{{ getLastMessage(user.userId) }}</div>
            </section>
          </div>
        </div>
        <!-- 右侧聊天室 -->
        <div
          ref="content"
          contenteditable="true"
          style="
            width: 75%;
            height: 73vh;
            margin: 0px auto;
            border: 10px solid rgb(218, 218, 221);
            border-left: none;
            /* box-shadow: 0px 0px 1px; */
            padding: 10px;
            overflow: auto;
          "
        >
          <div v-if="selectedUser">
            <div v-for="message in selectedUserMessages" :key="message.id" style="padding: 1rem 1rem;">
              <div
                v-if="message.systemMessageType == 'agent'"
                style="text-align: right"
              >
                <span class="userRightmsg" style="color: #ffffff">{{ message.msg }}</span
                ><img
                  style="width: 3rem; height: 3rem"
                  src="@/assets/agant.png"
                  alt=""
                />
              </div>
              <div v-else>
                <img
                  style="width: 3rem; height: 3rem"
                  src="@/assets/xiang.png"
                  alt=""
                /><span class="userLeftmsg">{{ message.msg }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div style="padding: 7px 20px" class="inpt">
        <el-input
          placeholder="请输入内容"
          v-model="inputText"
          clearable
        ></el-input>

        <el-button type="primary" @click="sendMessage" class="btn"
          >发送</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      webSocket: null,
      inputText: "",
      time: null,
      pushData: {
        code: 9002,
        msg: "",
        selfId: "",
      },
      userList: [], // 用户列表
      selectedUser: null, // 当前选中的用户
      userChatRecords: [],
      selectedUserMessages: [],
    };
  },
  computed: {
    userId() {
      return this.$store.getters.uid;
    },
    filteredUserList() {
      // 过滤具有唯一 username 和 userId 的用户
      const uniqueUsers = [];
      const uniqueUserIds = new Set();
      this.userList.forEach((user) => {
        if (!uniqueUserIds.has(user.userId)) {
          // 在这里为每个用户添加新属性 hasNewMessage，并初始化为 false
          user.hasNewMessage = false;
          uniqueUsers.push(user);
          uniqueUserIds.add(user.userId);
        }
      });
      return uniqueUsers;
    },
  },
  mounted() {
    this.initWebSocket();
  },
  methods: {
    initWebSocket() {
      // const path = "ws://206.237.30.11:3433/myHandler/";
      const path = "ws://185.232.92.15:3433/myHandler/";
      if (typeof WebSocket === "undefined") {
        alert("不支持WebSocket");
        return;
      }
      const id = Math.random();
      const admin = true;
      this.webSocket = new WebSocket(
        path + "?userId=" + this.userId + "&admin=" + admin
      );
      this.webSocket.onopen = this.onOpen;
      this.webSocket.onmessage = this.onMessage;
      this.webSocket.onerror = this.onError;
    },
    onOpen(event) {
      console.log(event);
      this.interval();
    },
    onMessage(event) {
      const data = JSON.parse(event.data);
      console.log(data, "ddd");

      // 处理接收到的消息
      if (data.code === 9002) {
        // 添加消息到用户消息列表中
        if (!this.userChatRecords[data.userId]) {
          this.userChatRecords[data.userId] = [];
        }
        this.userChatRecords[data.userId].push(data);

        this.userList.push(data);
        // 更新用户列表
        this.updateUserList(data.userId);
        // 如果当前选中用户就是发送消息的用户，则显示消息
        console.log(this.selectedUser);
        if (this.selectedUser && this.selectedUser.userId === data.userId) {
          this.selectedUserMessages.push(data);
        }
      } else if (data.code === 9001) {
        this.$refs.content.innerHTML += `<p style="color:#a09b9b;text-align:center;" >连接成功</p>`;
      }
    },
    onError(event) {
      console.log(event);
      this.$refs.content.innerHTML += `<p style="color:#a09b9b;text-align:center;" >连接错误</p>`;
      clearInterval(this.time);
    },
    sendMessage() {
      const v = this.inputText.trim();
      if (v || this.selectedUser.userId) {
        const messageData = {
          code: 9002,
          msg: v,
          userId: this.selectedUser.userId,
          systemMessageType: "agent",
        };
        this.webSocket.send(JSON.stringify(messageData));

        this.inputText = "";

        // 添加客服发送的消息到选中用户的消息记录列表中
        if (!this.userChatRecords[this.selectedUser.userId]) {
          this.$set(this.userChatRecords, this.selectedUser.userId, []);
        }
        if (messageData.code === 9002) {
          this.userChatRecords[this.selectedUser.userId].push(messageData);
          this.selectedUserMessages.push(messageData);
        }
      }
    },
    // 更新用户列表
    updateUserList(userId, username) {
      // 查找用户是否已经存在于用户列表中
      const existingUser = this.userList.find((user) => user.userId === userId);
      if (!existingUser) {
        // 如果用户不存在，添加到用户列表中
        this.userList.push({ userId });
      } else {
        // 如果用户存在，则更新用户的消息状态
        this.updateUserMessageStatus(userId);
      }
    },
    // 更新用户的消息状态
    updateUserMessageStatus(userId) {
      // 查找用户的消息记录
      const chatRecords = this.userChatRecords[userId];
      // 如果用户有消息记录
      if (chatRecords && chatRecords.length > 0) {
        // 检查用户的消息记录是否存在未读消息
        const hasUnreadMessages = chatRecords.some((record) => !record.read);
        // 更新用户的 hasNewMessage 属性
        const user = this.filteredUserList.find(
          (user) => user.userId === userId
        );
        if (user) {
          user.hasNewMessage = hasUnreadMessages;
        }
      }
    },
    selectUser(user) {
      // 选中用户，并显示其消息
      this.selectedUser = user;
      const chatRecords = this.userChatRecords[user.userId];
      if (chatRecords) {
        this.selectedUser.hasNewMessage = false;
        this.selectedUserMessages = chatRecords.filter(
          (record) => record.code === 9002
        );
      } else {
        this.selectedUserMessages = [];
      }
    },
    getLastMessage(userId) {
      const chatRecords = this.userChatRecords[userId];
      if (chatRecords && chatRecords.length > 0) {
        const lastMessage = chatRecords[chatRecords.length - 1];
        return lastMessage.msg;
      } else {
        return '';
      }
    },
    interval() {
      this.time = setInterval(() => {
        this.pushData.code = 9003;
        this.pushData.msg = "心跳";
        this.webSocket.send(JSON.stringify(this.pushData));
      }, 5000);
    },
  },
  beforeDestroy() {
    if (this.webSocket) {
      this.webSocket.close();
    }
    clearInterval(this.time);
  },
};
</script>

<style scoped>
.inpt {
  background: #f0e9e2;
  text-align: center;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
}
.left {
  width: 25%;
  height: 73vh;
  background-color: #067bf9;
}
.lists {
  cursor: pointer;
  color: #067bf9;
  height: 4rem;
  color: #1a1818;
  display: flex;
  padding-left: 6px;
  position: relative;
  align-items: center;
  justify-items: left;
  border-bottom: 1px solid #16151547;
}
.bubble {
  width: 10px;
  height: 10px;
  background-color: red;
  border-radius: 50%;
  position: absolute;
  top: 0.5rem; /* 调整气泡位置 */
  right: 0.5rem; /* 调整气泡位置 */
}
.userLeftmsg{
  color: chocolate;
    border-radius: 0.6rem;
    box-shadow: rgb(6, 123, 249) 0px 0px 2px;
    padding: 8px;
}
.userRightmsg{
  border-radius: 0.6rem;
    box-shadow: rgb(6, 123, 249) 0px 0px 2px;
    background-color: #067bf9;
    padding: 8px;
}
</style>